<template>
  <div class="orders-container">
    <a-card :bordered="false" class="orders-card">
      <!-- 订单搜索栏 -->
      <div class="search-bar">
        <a-input-search
          v-model:value="searchText"
          placeholder="输入商品标题或订单号进行搜索"
          style="width: 300px"
          @search="handleSearch"
        />
        <a-button type="link" @click="showMoreFilters = !showMoreFilters">
          更多筛选条件
          <DownOutlined v-if="!showMoreFilters" />
          <UpOutlined v-else />
        </a-button>
      </div>

      <!-- 订单状态标签页 -->
      <a-tabs v-model:activeKey="activeStatus" @change="handleTabChange">
        <a-tab-pane key="-1" tab="全部订单" />
        <a-tab-pane key="0" tab="待付款" />
        <a-tab-pane key="1" tab="待发货" />
        <a-tab-pane key="2" tab="待收货" />
        <a-tab-pane key="3" tab="已完成" />
        <a-tab-pane key="4" tab="已取消" />
        <a-tab-pane key="5" tab="已超时" />
      </a-tabs>

      <!-- 订单列表 -->
      <div v-if="orders.length > 0" class="order-list">
        <div v-for="order in orders" :key="order.id" class="order-item">
          <div class="order-header">
            <div class="order-info">
              <span class="order-time">{{ formatDate(order.createdAt) }}</span>
              <span class="order-number">订单号：{{ order.orderNo }}</span>
            </div>
            <div class="order-status" :class="getStatusClass(order.status)">
              {{ getStatusText(order.status) }}
            </div>
          </div>

          <div class="order-content">
            <div class="product-info">
              <span class="product-name">{{ order.productName }}</span>
            </div>
            <div class="order-amount">
              <div class="amount-label">实付款：</div>
              <div class="amount-value">
                ¥{{ order.totalAmount?.toFixed(2) }}
              </div>
            </div>
          </div>

          <div class="order-footer">
            <div class="order-actions">
              <!-- 待付款状态 -->
              <template v-if="order.status === 0">
                <a-button type="primary" @click="handlePay(order)"
                  >立即付款</a-button
                >
                <a-button @click="handleCancel(order)">取消订单</a-button>
              </template>
              <!-- 待发货状态 -->
              <template v-if="order.status === 1">
                <a-button @click="handleRemind(order)">提醒发货</a-button>
              </template>
              <!-- 待收货状态 -->
              <template v-if="order.status === 2">
                <a-button type="primary" @click="handleConfirm(order)"
                  >确认收货</a-button
                >
                <a-button @click="handleLogistics(order)">查看物流</a-button>
              </template>
              <!-- 已完成状态 -->
              <template v-if="order.status === 3">
                <a-button @click="handleReview(order)">评价</a-button>
                <a-button @click="handleBuyAgain(order)">再次购买</a-button>
              </template>
              <!-- 所有状态都显示订单详情 -->
              <a-button type="link" @click="handleViewDetail(order)">
                订单详情
              </a-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <a-empty
        v-else
        :description="getEmptyText(activeStatus)"
        :image="Empty.PRESENTED_IMAGE_SIMPLE"
      >
        <template #extra>
          <a-button type="primary" @click="$router.push('/')">去购物</a-button>
        </template>
      </a-empty>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import { Empty, message } from "ant-design-vue";
import { DownOutlined, UpOutlined } from "@ant-design/icons-vue";
import {
  getUserOrdersUsingGet,
  cancelOrderUsingPost,
  confirmReceiveUsingPost,
  payOrderUsingPost,
} from "@/api/orderController";
import type API from "@/api";
import { useRouter } from "vue-router";
// 状态管理
const activeStatus = ref("-1"); // -1表示全部订单
const searchText = ref("");
const showMoreFilters = ref(false);
const orders = ref<API.Order[]>([]);
const router = useRouter();

// 加载订单数据
const loadOrders = async () => {
  try {
    const res = await getUserOrdersUsingGet({
      status:
        activeStatus.value === "-1" ? undefined : Number(activeStatus.value),
    });
    if (res.data?.data) {
      orders.value = res.data.data;
    }
  } catch (error) {
    message.error("获取订单列表失败");
  }
};

// 处理标签页切换
const handleTabChange = (key: string) => {
  activeStatus.value = key;
};

// 处理搜索
const handleSearch = (value: string) => {
  searchText.value = value;
  loadOrders();
};

// 获取状态文本
const getStatusText = (status?: number) => {
  switch (status) {
    case 0:
      return "待付款";
    case 1:
      return "待发货";
    case 2:
      return "待收货";
    case 3:
      return "已完成";
    case 4:
      return "已取消";
    case 5:
      return "已超时";
    default:
      return "未知状态";
  }
};

// 获取状态样式类
const getStatusClass = (status?: number) => {
  switch (status) {
    case 0:
      return "status-pending-payment";
    case 1:
      return "status-pending-ship";
    case 2:
      return "status-pending-receive";
    case 3:
      return "status-completed";
    case 4:
      return "status-cancelled";
    case 5:
      return "status-timeout";
    default:
      return "";
  }
};

// 获取空状态文本
const getEmptyText = (status: string) => {
  switch (status) {
    case "0":
      return "没有待付款的订单";
    case "1":
      return "没有待发货的订单";
    case "2":
      return "没有待收货的订单";
    case "3":
      return "没有已完成的订单";
    case "4":
      return "没有已取消的订单";
    case "5":
      return "没有已超时的订单";
    default:
      return "暂无订单";
  }
};

// 格式化日期
const formatDate = (date?: string) => {
  if (!date) return "";
  return new Date(date).toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  });
};

// 订单操作处理函数
const handlePay = async (order: API.Order) => {
  try {
    await payOrderUsingPost(order);
    message.success("支付成功");
    loadOrders();
  } catch (error) {
    message.error("支付失败");
  }
};

const handleCancel = async (order: API.Order) => {
  try {
    await cancelOrderUsingPost({ id: order.id });
    message.success("取消成功");
    loadOrders();
  } catch (error) {
    message.error("取消失败");
  }
};

const handleConfirm = async (order: API.Order) => {
  try {
    await confirmReceiveUsingPost(order);
    message.success("确认收货成功");
    loadOrders();
  } catch (error) {
    message.error("确认收货失败");
  }
};

// 其他操作函数
const handleRemind = (order: API.Order) => {
  message.success("已提醒商家发货");
};

const handleLogistics = (order: API.Order) => {
  message.info("物流查询功能开发中");
};

const handleReview = (order: API.Order) => {
  message.info("评价功能开发中");
};

const handleBuyAgain = (order: API.Order) => {
  message.info("再次购买功能开发中");
};

const handleViewDetail = (order: API.Order) => {
  router.push(`/order/${order.id}`);
};

// 修改图片加载失败处理函数
const handleImageError = (e: Event) => {
  const img = e.target as HTMLImageElement;
  img.style.display = "none";
  console.error("图片加载失败:", img.src);
};

// 监听标签页变化
watch(activeStatus, () => {
  loadOrders();
});

// 初始加载
onMounted(() => {
  loadOrders();
});
</script>

<style scoped>
.orders-container {
  padding: 24px;
  background: #f5f5f5;
  min-height: 85vh;
  display: flex;
  justify-content: center;
}

.orders-card {
  width: 1200px;
  max-width: 100%;
}

.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 16px;
}

.order-list {
  margin-top: 20px;
}

.order-item {
  background: #fff;
  border-radius: 4px;
  margin-bottom: 16px;
  padding: 16px 24px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.order-header {
  display: flex;
  justify-content: space-between;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.order-info {
  display: flex;
  gap: 24px;
  color: #666;
}

.order-number {
  color: #999;
}

.order-status {
  font-weight: bold;
}

.order-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.product-name {
  color: #333;
  flex: 1;
}

.product-image {
  width: 50px;
  height: 50px;
  object-fit: cover;
}

.order-amount {
  text-align: right;
  margin-left: 24px;
}

.amount-label {
  color: #666;
  margin-bottom: 4px;
}

.amount-value {
  font-size: 20px;
  font-weight: bold;
  color: #ff4d4f;
}

.order-footer {
  display: flex;
  justify-content: flex-end;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.order-actions {
  display: flex;
  gap: 8px;
}

/* 状态颜色 */
.status-pending-payment {
  color: #ff4d4f;
}
.status-pending-ship {
  color: #faad14;
}
.status-pending-receive {
  color: #1890ff;
}
.status-completed {
  color: #52c41a;
}
.status-cancelled {
  color: #999;
}
.status-timeout {
  color: #d48806;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .orders-card {
    margin: 0 -12px;
    border-radius: 0;
  }

  .order-content {
    flex-direction: column;
    align-items: flex-start;
  }

  .order-amount {
    width: 100%;
    text-align: left;
    margin-top: 12px;
    margin-left: 0;
  }

  .order-actions {
    flex-wrap: wrap;
    width: 100%;
    justify-content: flex-end;
  }
}
</style>
